package com.sky.wsp.rabbitmq.controller;

import com.sky.wsp.rabbitmq.po.EventTypeEnum;
import com.sky.wsp.rabbitmq.po.MessageTypeEnum;
import com.sky.wsp.rabbitmq.po.MqMessage;
import com.sky.wsp.rabbitmq.po.TenantPo;
import com.sky.wsp.rabbitmq.producer.MqProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 租户事件消息
 */
@RestController
@RequestMapping("/tenant")
public class TenantMqController {

    @Autowired
    MqProducer mqProducer;

    @GetMapping("demo")
    public String demo() {
        return "demo";
    }

    @GetMapping(value = "/fanout")
    public String fanout(String name, EventTypeEnum event) {
        TenantPo tenantPo = getTenantPo(name);
        MqMessage<TenantPo> msg = getMsg(tenantPo, event);
        System.out.println("==> tenant fanout name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendFanout(msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/direct")
    public String direct(String name, EventTypeEnum event) {
        TenantPo tenantPo = getTenantPo(name);
        MqMessage<TenantPo> msg = getMsg(tenantPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> tenant direct routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.senddirectMail(routingKey, msg);
        return "ok: " + name;
    }

    @GetMapping(value = "/topic")
    public String topic(String name, EventTypeEnum event) {
        TenantPo tenantPo = getTenantPo(name);
        MqMessage<TenantPo> msg = getMsg(tenantPo, event);
        String routingKey = getRoutingKey(event);
        System.out.println("==> tenant topic routingKey: " + routingKey + ", name: " + name);

        // 通过MQ向三方应用发送消息
        mqProducer.sendtopicMail(routingKey, msg);
        return "ok: " + name;
    }

    private TenantPo getTenantPo(String name) {
        TenantPo tenantPo = new TenantPo();
        tenantPo.setId("tenantId");
        tenantPo.setName("name");
        return tenantPo;
    }

    private MqMessage<TenantPo> getMsg(TenantPo tenantPo, EventTypeEnum event) {
        return new MqMessage<>()
                .setMessageType(MessageTypeEnum.TENANT)
                .setEventType(event)
                .setData(tenantPo);
    }

    private String getRoutingKey(EventTypeEnum event) {
        return MessageTypeEnum.TENANT.name() + "." + event.name();
    }
}
